﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using IntroduceCompany.Models;
using IntroduceCompany.Singleton;
using IntroduceCompany.Util;
using System.IO;
using System.Web.UI.WebControls;
using System.Web.Routing;

namespace IntroduceCompany.Controllers
{
    [HandleError]
    [CheckModule(ConstantClass.Backend_AdminList_MenuID)]
    public class AdminController : BaseController
    {
        #region Account

        public IFormsAuthenticationService FormsService { get; set; }
        public IMembershipService MembershipService { get; set; }

        protected override void Initialize(RequestContext requestContext)
        {
            if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
            if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

            base.Initialize(requestContext);
        }
        
        public ActionResult LogOn()
        {
            if (Request.IsAuthenticated)
            {
                return RedirectToAction("AdminPage", "Admin");
            }
            else
            {
                return View("/Views/Backend/Admin/LogOn.aspx");
            }
        }

        [HttpPost]
        public ActionResult LogOn(LogOnAdminModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (MembershipService.ValidateUser(model.UserName, model.Password))
                {
                    FormsService.SignIn(model.UserName, model.RememberMe);
                    DataSingleton.GetAdminModels().UpdateLogInTime(model.UserName);
                    if (!String.IsNullOrEmpty(returnUrl))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("AdminPage", "Admin");
                    }
                }
                else
                {
                    //  ModelState.AddModelError("", "The user name or password provided is incorrect."); throw a mesg to view at the Html.ValidationSummary
                    ModelState.AddModelError("", "");
                }
            }
            // If we got this far, something failed, redisplay form
            return View("/Views/Backend/Admin/LogOn.aspx");
        }

        public ActionResult LogOff()
        {
            DataSingleton.GetAdminModels().UpdateLogOutTime(HttpContext.User.Identity.Name);
            FormsService.SignOut();
            return RedirectToAction("Index", "Home");
        }

        
        #endregion


//////////////////////////////////////////////////////////////////////


        #region AdminBackend


        /// <summary>
        /// enter the admin profile page.
        /// </summary>
        /// <returns></returns>
        [Authorize]
        public ActionResult AdminPage()
        {
            string username = HttpContext.User.Identity.Name;
            ViewData["CurrentUsername"] = username;
            ViewData["Gender"] = new SelectList(DataSingleton.GetGenderModels().GetGenderList("vi"), "GenderID", "GenderName");
            return View("/Views/Backend/Admin/AdminPage.aspx", DataSingleton.GetAdminModels().GetOneAdminEdit(username));
        }


        [Authorize]
        [HttpPost, ValidateInput(false), ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult AdminPageEdit(Administrator admin, String currentPass, String newPass, String confirmNewPass)
        {
            string username = HttpContext.User.Identity.Name;
            if (ModelState.IsValid && TryUpdateModel(admin))
            {
                    if (DataSingleton.GetAdminModels().CheckUsernameAndPassIsCorrect(username, currentPass))
                    {
                        if (newPass != "" && confirmNewPass != newPass)
                        {
                            ModelState.AddModelError("NoticePage", "Xác nhận mật khẩu không chính xác. Xin vui lòng làm lại.");
                        }
                        else
                        {
                            if (!DataSingleton.GetAdminModels().EditAdminAndChangePass(admin, newPass))
                            {
                                ModelState.AddModelError("NoticePage", "Có lỗi khi cập nhật thông tin admin. Xin vui lòng làm lại.");
                            }
                            else
                            {
                                ModelState.Clear();
                                ModelState.AddModelError("NoticePage", "Thông tin admin đã được cập nhật.");
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("NoticePage", "Mật khẩu hiện tại không chính xác. Xin vui lòng làm lại.");
                    }
            }

            ViewData["Gender"] = new SelectList(DataSingleton.GetGenderModels().GetGenderList("vi"), "GenderID", "GenderName");
            return View("/Views/Backend/Admin/AdminPage.aspx", DataSingleton.GetAdminModels().GetOneAdminEdit(admin.AdminID));
        }


        /// <summary>
        /// Get all admin
        /// </summary>
        /// <returns></returns>
        [Authorize(Roles = ConstantClass.autAdmin)]
        public ActionResult AdminListBackend()
        {

            return View("/Views/Backend/Admin/AdminList.aspx", DataSingleton.GetAdminModels().GetAdminList(HttpContext.User.IsInRole("1")));
        }


        /// <summary>
        /// Set Admin visible or not
        /// </summary>
        /// <param name="adminID"></param>
        /// <param name="visible"></param>
        /// <returns></returns>
        [Authorize(Roles = ConstantClass.autAdmin)]
        public ActionResult ChangeAdminVisible(int adminID, bool visible)
        {
            DataSingleton.GetAdminModels().ChangeAdminVisible(adminID, visible);
            return View("/Views/Backend/Admin/AdminList.aspx", DataSingleton.GetAdminModels().GetAdminList(HttpContext.User.IsInRole("1")));
        }


        [Authorize(Roles = ConstantClass.autAdmin)]
        public ActionResult AdminCreate()
        {
            ViewData["Role"] = new SelectList(DataSingleton.GetRoleModels().GetRoleList(), "RoleID", "RoleName");
            ViewData["Gender"] = new SelectList(DataSingleton.GetGenderModels().GetGenderList("vi"), "GenderID", "GenderName");

            return View("/Views/Backend/Admin/AdminCreate.aspx");
        }


        [Authorize(Roles = ConstantClass.autAdmin)]
        [HttpPost, ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult AdminCreate(Administrator admin)
        {
            string password = "";
            if (ModelState.IsValid)
            {
                if (TryUpdateModel(admin))
                {
                    if (DataSingleton.GetAdminModels().CheckUserNameIsExisted(admin.UserName))
                    {
                        ModelState.AddModelError("NoticePage", "Tên đăng nhập này đã được sử dụng. Xin vui lòng đổi tên khác.");
                        ViewData["Role"] = new SelectList(DataSingleton.GetRoleModels().GetRoleList(), "RoleID", "RoleName");
                        ViewData["Gender"] = new SelectList(DataSingleton.GetGenderModels().GetGenderList("vi"), "GenderID", "GenderName");

                        return View("/Views/Backend/Admin/AdminCreate.aspx", admin);
                    }
                    else
                    {
                        password = DataSingleton.GetAdminModels().CreateAdmin(admin);
                    }
                }

            }

            if (password != "")
            {
                ModelState.Clear();
                ModelState.AddModelError("NoticePage", "Admin mới đã được tạo với mật khẩu là  "+ password+"");
                
            }
            else
            {
                ModelState.AddModelError("NoticePage", "Có lỗi khị tạo admin");
            }

            ViewData["Role"] = new SelectList(DataSingleton.GetRoleModels().GetRoleList(), "RoleID", "RoleName");
            ViewData["Gender"] = new SelectList(DataSingleton.GetGenderModels().GetGenderList("vi"), "GenderID", "GenderName");

            return View("/Views/Backend/Admin/AdminCreate.aspx");
        }


        [Authorize(Roles = ConstantClass.autAdmin)]
        public ActionResult AdminEdit(int adminID)
        {
            ViewData["Role"] = new SelectList(DataSingleton.GetRoleModels().GetRoleList(), "RoleID", "RoleName");
            ViewData["Gender"] = new SelectList(DataSingleton.GetGenderModels().GetGenderList("vi"), "GenderID", "GenderName");

            Administrator admin = DataSingleton.GetAdminModels().GetOneAdminEdit(adminID);

            ViewData["CurrentUsername"] = admin.UserName;

            return View("/Views/Backend/Admin/AdminEdit.aspx",  admin);
        }


        [Authorize(Roles = ConstantClass.autAdmin)]
        [HttpPost,  ValidateInput(false), MultiButton(MatchFormKey = "action", MatchFormValue = "Lưu Admin"), ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult AdminEdit(Administrator admin, String currentUsername)
        {
            bool isEdited = false;
            if (ModelState.IsValid && TryUpdateModel(admin))
            {
                //Check username is change or not and username is duplicated or not
                if (currentUsername.ToLower() != admin.UserName.ToLower() && DataSingleton.GetAdminModels().CheckUserNameIsExisted(admin.UserName))
                {
                    ModelState.AddModelError("NoticePage", "Tên đăng nhập này đã được sử dụng. Xin vui lòng đổi tên khác.");
                    ViewData["CurrentUsername"] = currentUsername;
                }
                else
                {
                    isEdited = DataSingleton.GetAdminModels().EditAdmin(admin);

                    if (!isEdited)
                    {
                        ModelState.AddModelError("NoticePage", "Có lỗi khi cập nhật thông tin admin.");
                        ViewData["CurrentUsername"] = currentUsername;
                    }
                    else
                    {
                        ModelState.Clear();
                        ModelState.AddModelError("NoticePage", "Thông tin admin đã được cập nhật.");
                        ViewData["CurrentUsername"] = admin.UserName;
                    }
                }
            }
            else
            {
                ViewData["CurrentUsername"] = currentUsername;
            }

            ViewData["Role"] = new SelectList(DataSingleton.GetRoleModels().GetRoleList(), "RoleID", "RoleName");
            ViewData["Gender"] = new SelectList(DataSingleton.GetGenderModels().GetGenderList("vi"), "GenderID", "GenderName");
            return View("/Views/Backend/Admin/AdminEdit.aspx", DataSingleton.GetAdminModels().GetOneAdminEdit(admin.AdminID));
        }


        [Authorize(Roles = ConstantClass.autAdmin)]
        [HttpPost, ValidateInput(false), MultiButton(MatchFormKey = "action", MatchFormValue = "Tạo lại mật khẩu"), ValidateAntiForgeryToken(Salt = AntiKey.EditSalt)]
        public ActionResult ResetPassword(Administrator admin, String currentUsername)
        {

            string password = DataSingleton.GetAdminModels().ResetPassword(admin.AdminID);

            if (password != "")
            {
                ModelState.Clear();
                ModelState.AddModelError("NoticePage", "Admin đã được tạo lại mật khẩu mới là  " + password + "");
            }
            else
            {
                ModelState.AddModelError("NoticePage", "Có lỗi khị tạo lại mật khẩu. Xin vui lòng làm lại.");
            }

            ViewData["CurrentUsername"] = currentUsername;
            ViewData["Role"] = new SelectList(DataSingleton.GetRoleModels().GetRoleList(), "RoleID", "RoleName");
            ViewData["Gender"] = new SelectList(DataSingleton.GetGenderModels().GetGenderList("vi"), "GenderID", "GenderName");
            return View("/Views/Backend/Admin/AdminEdit.aspx", DataSingleton.GetAdminModels().GetOneAdminEdit(admin.AdminID));
        }

        #endregion

    }
}
